package com.zysf.library_boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zysf.library_boot.entity.BookInfo;
import com.zysf.library_boot.ov.ListBookInfoOV;
import com.zysf.library_boot.service.BookInfoService;
import com.zysf.library_boot.util.Result;
import com.zysf.library_boot.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/bookInfo")
public class BookInfoController {
    @Autowired
    BookInfoService bookInfoService;

    //书本轮播数据
    @RequestMapping("/books")
    public Result books() {
        QueryWrapper<BookInfo> qw=new QueryWrapper<>();
        qw.orderByDesc("total");
        qw.last("limit 18");
        return Result.ok(bookInfoService.list(qw));
    }
    //推荐书籍
    @RequestMapping("/recommendedBooks")
    public Result recommendedBooks() {
        QueryWrapper<BookInfo> qw=new QueryWrapper<>();
        qw.orderByAsc("total");
        qw.last("limit 8");
        List<BookInfo> recommendedBooks = bookInfoService.list(qw);
        return Result.ok(recommendedBooks);
    }
    @RequestMapping("/pageBook")
    public Result pageBook(ListBookInfoOV listBookInfoData){
        Page<BookInfo> page = new Page<>(listBookInfoData.getPage(), listBookInfoData.getSize());

        QueryWrapper<BookInfo> qw=new QueryWrapper<>();
        if (StringUtils.isNotBlank(listBookInfoData.getLanguage())) {
            qw.eq("language", listBookInfoData.getLanguage());
        }
        if (listBookInfoData.getTypeId() != null&&!"".equals(listBookInfoData.getTypeId())) {
            qw.eq("type_id", listBookInfoData.getTypeId());
        }
        Page<BookInfo> pageRes = bookInfoService.page(page,qw);
        return Result.ok(pageRes);
    }
    @RequestMapping("/getLibraryInfoById")
    public Result getLibraryInfoById(Integer id){
        BookInfo bookInfo = bookInfoService.getById(id);
        return Result.ok(bookInfo);
    }
    @RequestMapping("/getBookInfo")
    public Result getBookInfo(@RequestParam(required = false) String isbn,
                              @RequestParam(required = false) String name,
                              @RequestParam(required = false) Integer typeId,
                              @RequestParam int currentPage,
                              @RequestParam int pageSize) {
        QueryWrapper<BookInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(isbn)) {
            queryWrapper.like("isbn", isbn);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (typeId != null) {
            queryWrapper.eq("type_id", typeId);
        }
        Page<BookInfo> page = new Page<>(currentPage, pageSize);
        IPage<BookInfo> bookInfoPage = bookInfoService.page(page, queryWrapper);

        Map<String, Object> result = new HashMap<>();
        if (bookInfoPage != null) {
            result.put("records", bookInfoPage.getRecords());
            result.put("total", bookInfoPage.getTotal());
        } else {
            result.put("records", Collections.emptyList());
            result.put("total", 0);
        }
        return Result.ok(result);
    }

    @RequestMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestParam(name = "file", required = false) MultipartFile file, BookInfo bookInfo) {
        if (file!= null){
            String imgUrl = UploadFile.fileUrl(file);
            bookInfo.setPicture(imgUrl);
        }
        boolean k = bookInfoService.saveOrUpdate(bookInfo);
        return Result.ok(k);
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
        boolean i = bookInfoService.removeById(id);
        return Result.ok(i);
    }

    @RequestMapping("/batchDeleteBookInfo")
    public Result batchDeleteBookInfo(@RequestBody List<Integer> ids) {
        boolean j = bookInfoService.removeByIds(ids);
        return Result.ok(j);
    }

    @RequestMapping("/getBookInfoById")
    public Result getBookInfoById(@RequestParam Long id){
        BookInfo bookInfo = bookInfoService.getById(id);
        if (bookInfo != null) {
            return Result.ok(bookInfo);
        } else {
            return Result.fail("读者不存在");
        }
    }

    @RequestMapping("/getBookNames")
    public Result getBookNames(){
        List<BookInfo> bookInfoList = bookInfoService.list();
        return Result.ok(bookInfoList);
    }

    @RequestMapping("/getAllLanguages")
    public Result getAllLanguages(){
        List<BookInfo> bookInfoList = bookInfoService.list();
        Set<String> languageOptions = bookInfoList.stream()
                .map(BookInfo::getLanguage)
                .filter(language -> language != null && !language.isEmpty())
                .collect(Collectors.toSet());
        return Result.ok(new ArrayList<>(languageOptions));
    }

    @RequestMapping("/getAllTypes")
    public Result getAllTypes(){
        List<BookInfo> bookInfoList = bookInfoService.list();
        Set<Integer> typeIdOptions = bookInfoList.stream()
                .map(BookInfo::getTypeId)
                .filter(typeId -> typeId != null)
                .collect(Collectors.toSet());
        return Result.ok(new ArrayList<>(typeIdOptions));
    }

    @RequestMapping("/BookCount")
    public Result BookCount(){
        QueryWrapper<BookInfo> qwBookType =new QueryWrapper<>();
        qwBookType.select("type_id","count(*) as count");
        qwBookType.groupBy("type_id");
        List<Map<String,Object>>maps= bookInfoService.listMaps(qwBookType);
        return Result.ok(maps);
    }

    @RequestMapping("/getBookName")
    public Result getBookName(@RequestParam(required = false) String name,
                              @RequestParam int currentPage,
                              @RequestParam int pageSize) {
        QueryWrapper<BookInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        Page<BookInfo> page = new Page<>(currentPage, pageSize);
        IPage<BookInfo> bookInfoPage = bookInfoService.page(page, queryWrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("records", bookInfoPage.getRecords());
        result.put("total", bookInfoPage.getTotal());
        return Result.ok(result);
    }
}
